package com.neusoft.bizcore.notice.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.notice.system.converter.SystemNoticeConverter;
import com.neusoft.bizcore.notice.system.dto.NoticeConnectUserDTO;
import com.neusoft.bizcore.notice.system.dto.SystemNoticeDTO;
import com.neusoft.bizcore.notice.system.model.SystemNotice;
import com.neusoft.bizcore.notice.system.model.enums.SystemNoticeStatus;
import com.neusoft.bizcore.notice.system.repository.SystemNoticeRepository;
import com.neusoft.bizcore.notice.system.service.SystemNoticeService;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.bizcore.web.websocket.StompMessageService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SystemNoticeServiceImpl implements SystemNoticeService {

    @Autowired
    private SystemNoticeRepository systemNoticeRepository;
    @Autowired
    private SystemNoticeConverter systemNoticeConverter;
    @Autowired(required = false)
    private StompMessageService stompMessageService;

    @Override
    public List<SystemNoticeDTO> findAll(final Searchable searchable) {
        final List<SystemNotice> list = this.systemNoticeRepository.index(searchable);
        return this.systemNoticeConverter.toListDTO(list);
    }

    @Override
    public Page<SystemNoticeDTO> search(final Pageable pageable, final Searchable searchable, final UserBean user) {
        searchable.put("user", user.getUsername());
        final Page<SystemNotice> list = this.systemNoticeRepository.search(pageable, searchable);
        return this.systemNoticeConverter.toPageDTO(list);
    }

    @Override
    public void create(final SystemNoticeDTO dto) {
        final List<SystemNotice> models = new ArrayList<>();
        for (final String t : dto.getUserId()) {
            dto.setUser(new NoticeConnectUserDTO(t));
            final SystemNotice model = this.systemNoticeConverter.toModel(dto);
            models.add(model);
        }
        if (!models.isEmpty()) {
            this.systemNoticeRepository.saveAll(models);
            if (null != this.stompMessageService) {
                models.forEach(m -> {
                    final ArrayList<String> userId = new ArrayList<>();
                    userId.add(m.getUser().getUser());
                    this.stompMessageService.p2p("/notice", m, userId);
                });

            }
            SystemNoticeServiceImpl.log.info("调用stomp发送消息");
        }

    }

    @Override
    public SystemNoticeDTO update(final Long id, final SystemNoticeDTO dto) {
        SystemNotice model;
        try {
            model = this.systemNoticeRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.systemNoticeConverter.toModel(dto);
        this.systemNoticeRepository.save(model);

        return this.systemNoticeConverter.toDTO(model);
    }

    @Override
    public SystemNoticeDTO details(final Long id) {
        final SystemNotice model;
        try {
            model = this.systemNoticeRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        return this.systemNoticeConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {
        this.systemNoticeRepository.deleteById(id);
    }

    @Override
    public Integer getCurrentUnRead(final UserBean user) {
        if (user == null) {
            throw new UnitedException("没有用户信息");
        }
        final Searchable searchable = new Searchable();
        searchable.put("user", user.getUsername());
        searchable.put("isRead", SystemNoticeStatus.unRead.toString());
        final List<SystemNotice> list = this.systemNoticeRepository.index(searchable);
        return list.size();
    }

    @Override
    public List<String> findDistinctNoticeType() {
        return this.systemNoticeRepository.findDistinctNoticeType();
    }

    @Override
    public void notifyPage(String path, final String message) {
        if (!path.substring(0).equals("/")) {
            path = "/" + path;
        }
        this.stompMessageService.boardcast(path, message);
    }

}
